const db = require('../db/index')


// 新闻列表呈现
exports.getNewsList = (req,res)=>{
    const sqlStr = `select * from newsinfo where is_delete=0 order by newsId asc`
    db.query(sqlStr,(err,results)=>{
        if(err) return res.cc(err)
        res.send({
            status:0,
            message:'获取新闻列表成功',
            data:results
        })
    })


}

// 发布新闻
exports.addNews = (req,res)=>{
    const sqlStr = `select * from newsinfo where newsTitle=?`
    db.query(sqlStr,req.body.newsTitle,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length === 1 && results[0].newsTitle == req.body.newsTitle) return res.cc('新闻标题被占用')
        
        const sql =`insert into newsinfo set ?`
        db.query(sql,req.body,(err,results)=>{
            if(err) return res.cc(err)
            if(results.affectedRows !== 1) return res.cc('新增新闻失败')
            res.cc('新增新闻成功')
        })
    })
}
// 删除新闻
exports.deleteNews = (req,res)=>{
    const sqlStr = `update newsinfo set is_delete=1 where newsId=?`
    db.query(sqlStr,req.params.newsId,(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows !== 1) return res.cc('删除新闻失败')
        res.cc('删除新闻成功',0)
    })
}
// 修改新闻
exports.updateNewsById = (req,res)=>{
    const sqlStr = `select * from newsinfo where newsId<>? and newsTitle=?`
    db.query(sqlStr,[req.body.newsId,req.body.newsTitle,req.body.newsContent],(err,results)=>{
        if(err) return res.cc(err)
        if(results.length === 2) return res.cc('新闻标题和内容都被占用,请更换后重试')
        if(results.length === 1 && results[0].newsTitle == req.body.newsTitle && results[0].newsContent == req.body.newsContent){
            return res.cc('新闻标题和新闻内容都被占用')
        }
        if(results.length === 1 && results[0].newsTitle == req.body.newsTitle) return res.cc('新闻标题被占用')
        if(results.length === 1 && results[0].newsContent == req.body.newsContent) return res.cc('新闻内容被占用')
        const sql = `update newsinfo set ? where newsId =?`
        db.query(sql,[req.body,req.body.newsId],(err,results)=>{
            if(err) return res.cc(err)
            if(results.affectedRows !== 1) return res.cc('更新失败')
            res.cc('更新成功')
        })
    })
}

// 查询新闻
exports.getNewsById = (req,res)=>{
    const sqlStr = 'select * from newsinfo where newsTitle=?'
    db.query(sqlStr,req.params.newsTitle,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length !== 1) return res.cc('获取新闻数据失败')
        res.send({
            status:0,
            message:'获取数据成功',
            data:results[0]
        })
    })
    
}
